package com.fly.lambda.controller;

import com.fly.lambda.domain.FileInfo;
import com.fly.lambda.framework.utils.CommonUtils;
import com.fly.lambda.framework.utils.FileUtil;
import com.fly.lambda.framework.web.cache.CacheManage;
import com.fly.lambda.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Fly on 2016/7/21.
 */
@Controller
public class FileController {
    @Autowired
    CacheManage cacheManage;
    @Autowired
    FileService fileService;

    @RequestMapping("/manage/fileUpload")
    @ResponseBody
    public Map fileUpload(
            @RequestParam(value = "type", required = false, defaultValue = "")String type,
            HttpServletRequest request
    ) throws IOException {
        MultipartRequest multipartRequest = (MultipartRequest)request;
        List<MultipartFile> fileList = multipartRequest.getFiles("files[]");
        for(MultipartFile multipartFile: fileList){
            //文件保存
            String path = request.getServletContext().getRealPath("/").concat(cacheManage.getString(CacheManage.FILE_PATH));
            String name = CommonUtils.dateToStr(new Date(), "yyyyMMddHHmmss").concat(FileUtil.getExtension(multipartFile.getOriginalFilename()));
            FileUtil.save(path, name, multipartFile.getInputStream());
            //文件信息保存
            FileInfo file = new FileInfo();
            file.setFileName(name);
            file.setExtension(FileUtil.getExtension(multipartFile.getOriginalFilename()));
            file.setFileSize(multipartFile.getSize());
            file.setFilePath(path.concat(name));
            file.setFileUrl(cacheManage.getString(CacheManage.FILE_PATH).concat(name));
            fileService.saveFile(file);
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("result", "success");
        return map;
    }

}
